<template>
  <div>
    <!--最外层容器-->
<!--    <el-button type="warning" @click="testButton">按钮</el-button>-->
    <el-container>
      <!--侧边栏-->
      <el-aside v-if="!isMobile" :width="asideWidth" style=" min-height: 100vh; background-color: #001529">
        <!--logo区域-->
        <div class="logo" @click="$router.push('/')">
          <img src="@/assets/logo.png" alt="" style="width: 40px; height: 40px;">
          <span class="logo-title">小区消防检查</span>
        </div>
        <!--菜单栏-->
        <FiresafeMenu />
      </el-aside>
      <!--移动模式抽屉侧边栏-->
      <el-drawer v-if="isMobile" :visible.sync="drawerVisible" :with-header="false" direction="ltr" :show-close="false" size="50%">
        <el-aside width="100%" style=" min-height: 100vh; background-color: #001529">
          <!--logo区域-->
          <div class="logo" @click="$router.push('/')">
            <img src="@/assets/logo.png" alt="" style="width: 40px; height: 40px;">
            <span class="logo-title">小区消防检查</span>
          </div>
          <!--菜单栏-->
          <FiresafeMenu />
        </el-aside>
      </el-drawer>

      <el-container>
        <!--头部横栏-->
        <el-header style="color: white; background-color: #c41335;" class="mobile-mode-header">
          <!--手机模式显示logo-->
          <div v-if="isMobile" class="logo mobile-mode-logo" @click="$router.push('/')">
            <img src="@/assets/logo.png" alt="" style="width: 40px; height: 40px;">
          </div>

          <!--展开收缩按钮-->
          <i v-if="isMobile" :class="collapseIcon" style="font-size: 26px; cursor: pointer" @click="handleCollapse(!drawerVisible)"></i>

          <el-breadcrumb separator="/" style="margin-left: 0.3rem;">
<!--            <el-breadcrumb-item :to="{ path: '/' }"><span style="color: white">首页</span></el-breadcrumb-item>-->
            <el-breadcrumb-item :to="{ path: $route.path }">
              <span style="color: white">{{ $route.meta.name }}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>

          <div style="flex: 1; display: flex; width: 0; align-items: center; justify-content: flex-end">
            <!-- 天气-->
            <span style="margin: 0 0.2rem 0 0.3rem; cursor: default;">{{ weather }}</span>
            <span style="margin-right: 0.3rem; cursor: default;">{{ temperature }}℃</span>
            <!-- 全屏-->
            <i class="el-icon-full-screen" style="font-size: 26px; cursor: pointer" @click="handleFull"></i>
            <!--消息通知-->
            <el-dropdown :class="['message-dropdown', {'fixed-message-dropdown': isMobile}]" :placement="isMobile ? 'top' : 'bottom'">
              <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="message">
                <i class="el-icon-message-solid headerIcon"></i>
              </el-badge>
              <el-dropdown-menu>
                <el-empty v-if="!unreadCount" description="暂无消息" :image-size="100"></el-empty>
                <el-dropdown-item v-else v-for="item in unreadList" :key="item.id"
                                  @click.native="$router.push({path: '/message', query: {id: item.id}})">
                  <div class="messageContent" :style="{color: levelColor[item.level]}">
                    {{item.createdTime}} {{ item.title }}
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!--用户-->
            <el-dropdown class="user-dropdown" placement="bottom" style="color: white;">
              <div style="display: flex; align-items: center; cursor: pointer;">
                <el-image :src="loginUser.avatar" alt=""
                          style="width: 40px; height: 40px; border-radius: 50%; margin-right: 5px">
                  <!--加载失败内容-->
                  <div slot="error"
                       style="width:100%; height: 100%; display: flex; align-items: center; justify-content: center;">
                    <i class="el-icon-user-solid" style="font-size: 25px"></i>
                  </div>
                </el-image>
                <template v-if="!isMobile">
                  <span v-if="loginUser.userName!==undefined">
                  {{ loginUser.userName + ' &nbsp;&nbsp;' + loginUser.role }}</span>
                  <span v-else>未登录</span>
                </template>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="loginUser.role" @click.native="$router.push('/person')">
                  个人信息
                </el-dropdown-item>
                <el-dropdown-item v-if="loginUser.role" @click.native="$router.push('/changePassword')">
                  修改密码
                </el-dropdown-item>
                <el-dropdown-item v-if="loginUser.role" @click.native="logout">
                  退出登录
                </el-dropdown-item>
                <el-dropdown-item v-else @click.native="$router.push('/login')">
                  去登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-header>
        <!--主体部分-->
        <el-main class="mobile-mode-main">
          <router-view @update:user="updateUser"/>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>

import axios from "axios";
import urgentLevelColor from "@/utils/constants/UrgentLevelColor";
import MessageFilterType from "@/utils/constants/MessageFilterType";
import FiresafeMenu from "@/components/FiresafeMenu.vue";
import {mobileWidth} from "@/utils/mobileWidth";

export default {
  name: 'ManagerView',
  data() {
    return {
      // 改变为移动端的宽度
      mobileWidth: mobileWidth,
      // 是否开启移动端的适配
      isMobile: false,
      //未读消息个数
      unreadCount: 1,
      //未读消息列表
      unreadList: [
        {id: 4, title: '消息111111111111111111111111111111111111111111111111111', level: 2},
      ],
      weather: '',
      temperature: '',
      drawerVisible: false, // 根据窗口大小初始化侧边栏的折叠状态
      asideWidth: '200px', //侧边栏默认宽度
      collapseIcon: 'el-icon-s-unfold',
      loginUser: JSON.parse(localStorage.getItem('user')) || {},
      levelColor: urgentLevelColor,
    }
  },
  //vue实例创建后，还没渲染数据时，自动执行的操作
  created() {
  },
  //页面完成渲染后自动执行的操作
  mounted() {
    this.getWeather()
    this.initSSE()
    this.getUnreadCount()
    this.getUnreadList()
    this.handleResize()
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // testButton() {
    // },
    //获取未读消息个数
    getUnreadCount() {
      this.$request.get('/message/getUnreadCount').then(res => {
        if (res.code === 200) {
          this.unreadCount = res.data
        }
      })
    },
    //获取未读消息列表
    getUnreadList() {
        this.$request.get('/message/list/' + MessageFilterType.unread).then(res => {
          if (res.code === 200) {
            this.unreadList = res.data
          }
        })
    },
    //初始化SSE对象，设置接收消息等逻辑
    initSSE() {
      const sse = new EventSource(this.$baseUrl + '/message/getEmitter?token=' + this.loginUser.token)
      console.log('初始化SSE对象', sse)
      sse.onmessage = event => {
        const message = JSON.parse(event.data)
        console.log('收到消息:', message)
        //收到消息重新获取未读消息
        this.getUnreadCount()
        this.getUnreadList()
      }
      sse.onerror = event => {
        console.log('sse连接失败', event)
        sse.close()
      }
    },
    //接收子组件的用户更新消息
    updateUser() {
      // this.loginUser=loginUser//传递引用导致两个loginUser引用同一个对象，造成两者同时变化，这是不希望的
      // this.loginUser=JSON.parse(JSON.stringify(loginUser))//深克隆就能解决这个问题
      this.loginUser = JSON.parse(localStorage.getItem('user')) || {}  //相当于这个方法
      this.getUnreadCount()
      this.getUnreadList()
    },
    //获取天气
    getWeather() {
      axios.get('https://restapi.amap.com/v3/weather/weatherInfo?city=522600&key=bcbae5c8cddb56042734bd30660528b5').then(res => {
        this.weather = res.data.lives[0].weather
        this.temperature = res.data.lives[0].temperature
      })
    },
    // 根据窗口宽度改变页面
    handleResize() {
      this.isMobile = window.innerWidth < this.mobileWidth
    },
    // 点击收缩或展开
    handleCollapse(drawerVisible) {
      this.drawerVisible = drawerVisible;
      // this.asideWidth = this.isCollapse ? '64px' : '200px';
      // this.collapseIcon = this.isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'

    },
    handleFull() {
      if (document.fullscreen) {
        document.exitFullscreen();
      } else {
        document.documentElement.requestFullscreen();
      }
    },
    logout() {
      localStorage.removeItem('user')
      this.$router.push('/login')
    }
  },
  components: {FiresafeMenu}
}
</script>

<style scoped>

.el-aside {
  transition: width .3s;
  box-shadow: 2px 0 6px rgba(0, 21, 41, .35);
}

.logo {
  height: 60px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.logo:hover {
  color: #c41335;
}

.logo-title {
  margin-left: 5px;
  font-size: 20px;
  transition: all 0.3s;
}

.mobile-mode-logo {
  margin-right: 0.3rem;
}

.el-header {
  box-shadow: 2px 0 6px rgba(0, 21, 41, .35);
  display: flex;
  align-items: center;
}

.message-dropdown {
  color: white;
}

.fixed-message-dropdown {
  position: fixed;
  bottom: 10vh;
  right: 10vw;
  z-index: 1000;
  background-color: #c41335;
  width: 2.5rem;
  height: 2.5rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.7);
}

.user-dropdown {
  margin-left: 0.3rem;
}

.message {
  margin: 0 0.3rem;
  cursor: pointer;
}

.headerIcon {
  font-size: 20px;
}

.messageContent {
  width: 10em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: bold;
}

@media (max-width: 700px) {
  .mobile-mode-header {
    position: fixed;
    width: 100%;
    z-index: 999;
  }
  .mobile-mode-main {
    position: relative;
    top: 60px;
  }
}
</style>
